package com.yygo.webapp.controller;

import com.yygo.Constants;
import com.yygo.model.*;
import com.yygo.model.vo.BondCompanyVO;
import com.yygo.service.BondManager;
import com.yygo.service.LoanProductManager;
import com.yygo.service.RoleManager;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/bondCompanyform*")
public class BondCompanyFormController extends BaseFormController {
  @Autowired
  private LoanProductManager loanProductManager;


    @Autowired
    private BondManager bondManager;

    @Autowired
    private RoleManager roleManager;

    public BondCompanyFormController() {
        setCancelView("redirect:bondCompanies");
        setSuccessView("redirect:bondCompanies");
    }

    @ModelAttribute
    @RequestMapping(method = RequestMethod.GET)
    protected BondCompany showForm(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
          BondCompany bondCompany = bondManager.loadBond(new Long(id));

            return bondCompany;
        }

        return new BondCompany();
    }
  @RequestMapping(value = "/children", method = RequestMethod.GET)
  @ResponseBody
  public List<BondCompanyVO> getChildren(@RequestParam(required = true, value = "bondId") Long bondId, HttpServletRequest request ) {
    BondCompanyVO bondCompany = bondManager.loadChildTree(bondId);
    List<BondCompanyVO> list = bondCompany.getChildren();

    return list;
  }
  @RequestMapping(value = "/all/children", method = RequestMethod.GET)
  @ResponseBody
  public List<BondCompanyVO> getAllChildren(HttpServletRequest request ) {
    List<BondCompanyVO> companies = bondManager.loadAllChildTree();
    return companies;
  }
  @ModelAttribute("availableProviders")
  protected List<LabelValue> getAvailableProviders(){
    List<LabelValue> list = new ArrayList<LabelValue>();
    List<BondCompany> bondCompanies = bondManager.getAll();
    for (BondCompany bondCompany : bondCompanies) {
      list.add(new LabelValue(bondCompany.getName(),"" +  bondCompany.getId()));
    }
    return list;
  }
  @ModelAttribute("availableProduct")
  protected Set<LabelValue> getAvailableProduct() {
    Set<LabelValue> list = new HashSet<LabelValue>();
    List<LoanProduct> products = loanProductManager.getAll();
    for (LoanProduct product : products) {
      list.add(new LabelValue(product.getProductName(), "" + product.getId()));
    }
    return list;
  }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(BondCompany bondCompany, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
    throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        if (validator != null) { // validator is null during testing
            validator.validate(bondCompany, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "bondCompanyform";
            }
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (bondCompany.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();

        bondCompany.getLoanProducts().clear();
        if (bondCompany.getProductIds() != null ){
            Set<LoanProduct> list = new HashSet<>();
            for (Long productId : bondCompany.getProductIds()){
                list.add(loanProductManager.get(productId));
            }

            bondCompany.setLoanProducts(list);
        }

      if(bondCompany.getParentId() != null){
        bondCompany.setParent(bondManager.get(bondCompany.getParentId()));
      }

        if (request.getParameter("delete") != null) {
            bondManager.remove(bondCompany.getId());
            saveMessage(request, getText("bondCompany.deleted", locale));
        } else {
            User user = bondCompany.getBondUser();
            User nameUser = getUserManager().getUserByUsername(user.getUsername());
            User emailUser = getUserManager().getUserByEmail(user.getEmail());
            if (nameUser!=null && nameUser.getId()!=user.getId()){
                errors.rejectValue("bondUser.username", "errors.username.exist", new String[]{user.getUsername()}, "username is exist");
            }
            if (emailUser!=null && emailUser.getId()!=user.getId()){
                errors.rejectValue("bondUser.email", "errors.email.exist", new String[]{user.getEmail()}, "email is exist");
            }
            if (errors.hasErrors()) {
                copyErrors(request, errors);
                return "bondCompanyform";
            }
            /*if (isNew) {
                //bondCompany.setBondUser(user);
                bondManager.saveBond(bondCompany);
            }
          User user = bondCompany.getBondUser();
          user.setEnabled(true);
          user.getRoles().clear();
          user.addRole(roleManager.getRole(Constants.Bond_USER_ROLE));
            if (bondCompany.isMasterProvider() || bondCompany.isSlaveProvider()) {
                user.addRole(roleManager.getRole(Constants.Insurance_ROLE));
            } else {
                user.getRoles().remove(roleManager.getRole(Constants.Insurance_ROLE));
            }
          user.setBondCompany(bondCompany);
          user = getUserManager().saveUser(user);
            bondCompany.setBondUser(user);*/
            bondManager.saveBond(bondCompany);

            String key = (isNew) ? "bondCompany.added" : "bondCompany.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                success = "bondCompanyform";
            }
        }

        return success;
    }

    private void copyErrors(HttpServletRequest request, BindingResult errors) {
        List<ObjectError> errorMessages = errors.getAllErrors();
        for (ObjectError err : errorMessages) {
            saveError(request, getText(err.getCode(), err.getArguments(), request.getLocale()));
        }
    }

    @ModelAttribute
    public Set<Dealer> getDealers(HttpServletRequest request) {
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            return bondManager.getDealers(new Long(id));
        }

        return new HashSet<>();
    }

  @ModelAttribute
    public Set<LoanProduct> getProducts(HttpServletRequest request) {
      String id = request.getParameter("id");

      if (!StringUtils.isBlank(id)) {
        BondCompany bondCompany = bondManager.load(new Long(id));
        return bondCompany.getLoanProducts();
      }

    return new HashSet<>();
  }
}
